/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.rpc.syncUser.user;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.service.rpc.SystemSettingRpcService;
import com.je.common.base.util.ArrayUtils;
import com.je.common.base.util.DateUtils;
import com.je.common.base.util.JEUUID;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.exception.AccountException;
import com.je.rbac.exception.DepartmentUserException;
import com.je.rbac.model.syncdata.SyncUser;
import com.je.rbac.rpc.AccountRpcService;
import com.je.rbac.rpc.SyncUserDataRpcService;
import com.je.rbac.rpc.syncUser.util.StreamEx;
import com.je.rbac.rpc.syncUser.util.SyncParserUserUtil;
import com.je.rbac.service.account.RbacAccountService;
import com.je.rbac.service.company.RbacDepartmentService;
import com.je.rbac.service.company.RbacDepartmentUserService;
import com.je.rbac.service.organization.OrgType;
import com.je.rbac.service.role.RbacAccountRoleService;
import org.apache.commons.lang.StringUtils;
import org.apache.servicecomb.provider.pojo.RpcSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import static jdk.nashorn.internal.objects.NativeMath.max;

@RpcSchema(schemaId = "syncUserDataRpcService")
public class SyncUserDataRpcServiceImpl implements SyncUserDataRpcService {

    @Autowired
    private AccountRpcService accountRpcService;
    @Autowired
    private RbacDepartmentUserService rbacDepartmentUserService;
    @Autowired
    private RbacAccountService rbacAccountService;
    @Autowired
    private RbacDepartmentService rbacDepartmentService;
    @Autowired
    private SystemSettingRpcService systemSettingRpcService;
    @Autowired
    private BeanService beanService;
    @Autowired
    private MetaService metaService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private RbacAccountRoleService rbacAccountRoleService;

    private static List<DynaBean> rbacUserList;
    private static List<DynaBean> rbacDepartmentList;
    private static DynaBean syncUserLogDynaBean;

    private final static ExecutorService EXECUTORS = Executors.newFixedThreadPool(5);
    private static final Logger logger = LoggerFactory.getLogger(SyncUserDataRpcServiceImpl.class);
    private final static String TYPE = "user";

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public BaseRespResult syncUserData(List<SyncUser> userData) {
        //人员表，部门人员表，账号表，账号部门表，角色部门人员表
        //拿到所有用户部门数据，
        if (userData == null || userData.size() == 0) {
            return BaseRespResult.errorResult("用户数据为空，请检查！");
        }
        //检查是否主键重复
        if (StreamEx.checkCFNumByUserId(userData) > 0) {
            return BaseRespResult.errorResult("JE_RBAC_USER_ID 主键字段重复，请检查！");
        }
        //先查出所有人员、部门信息缓存起来
        rbacUserList = metaService.select("JE_RBAC_USER", ConditionsWrapper.builder());
        rbacDepartmentList = metaService.select("JE_RBAC_DEPARTMENT", ConditionsWrapper.builder());
        //每同步一次生成一次记录日志
        syncUserLogDynaBean = new DynaBean("JE_RBAC_SYNC_LOG", false);
        //日志类型为user
        syncUserLogDynaBean.setStr("LOG_CZLX", TYPE);
        Object obj = new Object();
        for (SyncUser eachSyncBean : userData) {
            EXECUTORS.execute(() -> {
                synchronized (obj) {
                    //根据传过来数据构建基本信息
                    DynaBean deptUserBean = SyncParserUserUtil.buildDynaBean(eachSyncBean);
                    syncUserLogDynaBean.setStr("LOG_TBSFCG", "1");
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("用户姓名", deptUserBean.getStr("USER_NAME"));
                    jsonObject.put("用户Id", deptUserBean.getStr("JE_RBAC_USER_ID"));
                    jsonObject.put("用户编码", deptUserBean.getStr("USER_CODE"));
                    jsonObject.put("部门名称", deptUserBean.getStr(""));
                    jsonObject.put("部门Id", deptUserBean.getStr("JE_RBAC_DEPARTMENT_ID"));
                    // 校验用户账号，手机号，邮箱是否唯一(手机号，邮箱暂不校验)
                    if (!rbacDepartmentUserService.checkUserCodeUnique(deptUserBean, rbacUserList)) {
                        //编码重复的输出日志
                        syncUserLogDynaBean.setStr("LOG_TBSFCG", "0");
                        jsonObject.put("失败原因", "用户编码重复");
                        if (syncUserLogDynaBean.getStr("LOG_SBYY") != null) {
                            if (!syncUserLogDynaBean.getStr("LOG_SBYY").contains("用户编码重复")) {
                                syncUserLogDynaBean.setStr("LOG_SBYY", syncUserLogDynaBean.getStr("LOG_SBYY") + "," + "用户编码重复");
                            }
                        } else {
                            syncUserLogDynaBean.setStr("LOG_SBYY", "用户编码重复");
                        }
                        if (syncUserLogDynaBean.getStr("LOG_SBXX") != null) {
                            if (!syncUserLogDynaBean.getStr("LOG_SBXX").contains(jsonObject.toJSONString())) {
                                syncUserLogDynaBean.setStr("LOG_SBXX", syncUserLogDynaBean.getStr("LOG_SBXX") + "," + jsonObject.toJSONString());
                            }
                        } else {
                            syncUserLogDynaBean.setStr("LOG_SBXX", jsonObject.toJSONString());
                        }
                        logger.warn("用户编码重复：" + "用户名：" + deptUserBean.getStr("USER_NAME") + "-----用户Id" + deptUserBean.getStr("JE_RBAC_USER_ID"));

                        return;
                    }
                    //校验用户所属部门
                    List<DynaBean> departmentList = rbacDepartmentList.stream().filter(dept -> dept.getStr("JE_RBAC_DEPARTMENT_ID").equals(deptUserBean.getStr("JE_RBAC_DEPARTMENT_ID"))).collect(Collectors.toList());
                    if (departmentList.isEmpty()) {
                        //输出日志 部门不存在
                        syncUserLogDynaBean.setStr("LOG_TBSFCG", "0");
                        jsonObject.put("失败原因", "导入人所在部门不存在");

                        if (syncUserLogDynaBean.getStr("LOG_SBYY") != null) {
                            if (!syncUserLogDynaBean.getStr("LOG_SBYY").contains("导入人所在部门不存在")) {
                                syncUserLogDynaBean.setStr("LOG_SBYY", syncUserLogDynaBean.getStr("LOG_SBYY") + "," + "导入人所在部门不存在");
                            }
                        } else {
                            syncUserLogDynaBean.setStr("LOG_SBYY", "导入人所在部门不存在");
                        }
                        if (syncUserLogDynaBean.getStr("LOG_SBXX") != null) {
                            if (!syncUserLogDynaBean.getStr("LOG_SBXX").contains(jsonObject.toJSONString())) {
                                syncUserLogDynaBean.setStr("LOG_SBXX", syncUserLogDynaBean.getStr("LOG_SBXX") + "," + jsonObject.toJSONString());
                            }
                        } else {
                            syncUserLogDynaBean.setStr("LOG_SBXX", jsonObject.toJSONString());
                        }
                        logger.warn("导入人所在部门不存在：" + "用户名：" + deptUserBean.getStr("USER_NAME") + "-----用户Id" + deptUserBean.getStr("JE_RBAC_USER_ID") + "-----部门Id" + deptUserBean.getStr("JE_RBAC_DEPARTMENT_ID"));
                        return;
                    }
                    //查找与系统对应人员，没有新增，有则修改
                    List<DynaBean> userBeanList = rbacUserList.stream().filter(user -> user.get("JE_RBAC_USER_ID").equals(deptUserBean.getStr("JE_RBAC_USER_ID"))).collect(Collectors.toList());
                    if (userBeanList.isEmpty()) {
                        doSave(deptUserBean, departmentList);
                    } else {
                        // 重写修改方法--处理 修改部门人员，需拿人员主键+部门主键查找并更新
                        doUpdate(deptUserBean, departmentList, userBeanList);
                    }
                }
                metaService.update(syncUserLogDynaBean);
            });
        }
        //保存同步日志
        commonService.buildModelCreateInfo(syncUserLogDynaBean);
        metaService.insert(syncUserLogDynaBean);
        return BaseRespResult.successResult("正在同步中...");
    }

    @Transactional(rollbackFor = Exception.class)
    public void doSave(DynaBean viewDeptUserBean, List<DynaBean> departmentList) throws DepartmentUserException {
        //部门id
        String departmentId = viewDeptUserBean.getStr("JE_RBAC_DEPARTMENT_ID");
//        DynaBean deptBean = metaService.selectOne("JE_RBAC_DEPARTMENT", ConditionsWrapper.builder().eq("JE_RBAC_DEPARTMENT_ID", departmentId));
        if (departmentList != null && !departmentList.isEmpty()) {
            if (departmentList.get(0).getStr("SY_STATUS").equals("0")) {
                throw new DepartmentUserException("部门状态已禁用,请确认！");
            }

            DynaBean userBean = new DynaBean("JE_RBAC_USER", false);
            DynaBean userBeanTable = beanService.getResourceTable("JE_RBAC_USER");
            List<DynaBean> userColumns = userBeanTable.getDynaBeanList(BeanService.KEY_TABLE_COLUMNS);
            for (DynaBean eachColumnBean : userColumns) {
                if (viewDeptUserBean.containsKey(eachColumnBean.getStr("TABLECOLUMN_CODE"))) {
                    userBean.set(eachColumnBean.getStr("TABLECOLUMN_CODE"), viewDeptUserBean.get(eachColumnBean.getStr("TABLECOLUMN_CODE")));
                }
            }
            commonService.buildModelCreateInfo(userBean);
            userBean.set("SY_ORG_ID", departmentList.get(0).getStr("SY_ORG_ID"));

            metaService.insert(userBean);
            //同步增加到缓存
            rbacUserList.add(userBean);

            //构建排序 如果部门人人员关系表有这个部门用这个表排序字段排，如果没有则用部门表部门人员排序字典排排序
            List<Map<String, Object>> countList = metaService.selectSql("SELECT MAX(SY_ORDERINDEX) AS MAX_COUNT FROM JE_RBAC_DEPTUSER WHERE JE_RBAC_DEPARTMENT_ID ='" + departmentId + "'");
            int count = 0;
            if (countList.size() <= 0) {
                count = rbacDepartmentList.stream().filter(dept -> dept.getStr("JE_RBAC_DEPARTMENT_ID").equals(departmentId)).mapToInt(dept -> new Integer(String.valueOf(dept.getStr("DEPARTMENT_USER_ORDERINDEX")))).max().orElse(0);
//                countList = metaService.selectSql("SELECT MAX(DEPARTMENT_USER_ORDERINDEX) AS MAX_COUNT FROM JE_RBAC_DEPARTMENT WHERE JE_RBAC_DEPARTMENT_ID ='" + departmentId + "'");
            } else {
                count = Integer.valueOf(countList.get(0).get("MAX_COUNT").toString());
            }

            DynaBean deptUserBeanTable = beanService.getResourceTable("JE_RBAC_DEPTUSER");
            List<DynaBean> deptUserColumns = deptUserBeanTable.getDynaBeanList(BeanService.KEY_TABLE_COLUMNS);
            DynaBean deptUserBean = new DynaBean("JE_RBAC_DEPTUSER", false);
            for (DynaBean eachColumnBean : deptUserColumns) {
                if (viewDeptUserBean.containsKey(eachColumnBean.getStr("TABLECOLUMN_CODE"))) {
                    deptUserBean.set(eachColumnBean.getStr("TABLECOLUMN_CODE"), viewDeptUserBean.get(eachColumnBean.getStr("TABLECOLUMN_CODE")));
                }
            }
            deptUserBean.set("JE_RBAC_USER_ID", userBean.getStr("JE_RBAC_USER_ID"));
            deptUserBean.set("JE_RBAC_DEPARTMENT_ID", departmentId);
            deptUserBean.setStr("SY_GROUP_COMPANY_ID", departmentList.get(0).getStr("SY_GROUP_COMPANY_ID"));
            deptUserBean.setStr("SY_GROUP_COMPANY_NAME", departmentList.get(0).getStr("SY_GROUP_COMPANY_NAME"));
            deptUserBean.set("DEPTUSER_MAIN_CODE", "1");
            deptUserBean.set("DEPTUSER_MAIN_NAME", "主部门");
            deptUserBean.set("SY_STATUS", "1");//默认开启
            deptUserBean.set("SY_ORDERINDEX", count + 1);
            commonService.buildModelCreateInfo(deptUserBean);
            metaService.insert(deptUserBean);

            //同步所属部门主管领导信息
            if (!Strings.isNullOrEmpty(deptUserBean.getStr("DEPTUSER_SFZG_CODE"))) {
                if (Strings.isNullOrEmpty(departmentList.get(0).getStr("DEPARTMENT_MAJOR_ID")) && deptUserBean.getStr("DEPTUSER_SFZG_CODE").equals("1")) {
                    //更新部门主管信息
                    metaService.executeSql("UPDATE JE_RBAC_DEPARTMENT SET DEPARTMENT_MAJOR_ID={0},DEPARTMENT_MAJOR_NAME={1} WHERE JE_RBAC_DEPARTMENT_ID={2} ", userBean.getStr("JE_RBAC_USER_ID"), userBean.getStr("USER_NAME"), departmentId);
                    //更新部门缓存
                    rbacDepartmentList = metaService.select("JE_RBAC_DEPARTMENT", ConditionsWrapper.builder());
                } else if (!Strings.isNullOrEmpty(departmentList.get(0).getStr("DEPARTMENT_MAJOR_ID"))) {
                    //判断是否是主管,若 是主管
                    if (deptUserBean.getStr("DEPTUSER_SFZG_CODE").equals("1")) {
                        //判断当前人是否在主管中，不在则追加
                        if (!departmentList.get(0).getStr("DEPARTMENT_MAJOR_ID").contains(userBean.getStr("JE_RBAC_USER_ID"))) {
                            List<String> majorIdList = Arrays.asList(departmentList.get(0).getStr("DEPARTMENT_MAJOR_ID").split(ArrayUtils.SPLIT));
                            List<String> newMajorIdList = new ArrayList(majorIdList);
                            newMajorIdList.add(userBean.getStr("JE_RBAC_USER_ID"));
                            List<String> majorNameList = Arrays.asList(departmentList.get(0).getStr("DEPARTMENT_MAJOR_NAME").split(ArrayUtils.SPLIT));
                            List<String> newMajorNameList = new ArrayList(majorNameList);
                            newMajorNameList.add(userBean.getStr("USER_NAME"));
                            metaService.executeSql("UPDATE JE_RBAC_DEPARTMENT SET DEPARTMENT_MAJOR_ID={0},DEPARTMENT_MAJOR_NAME={1} WHERE JE_RBAC_DEPARTMENT_ID={2} ", StringUtils.join(newMajorIdList, ","), StringUtils.join(newMajorNameList, ","), departmentId);
                            //更新部门缓存
                            rbacDepartmentList = metaService.select("JE_RBAC_DEPARTMENT", ConditionsWrapper.builder());
                        }
                    }
                }
            }
            //同步创建账号 状态默认为 开启
            JSONArray array = new JSONArray();
            JSONObject userObj = new JSONObject();
            userObj.put("status", "1");
            userObj.put("departmentId", departmentId);
            userObj.put("userId", deptUserBean.getStr("JE_RBAC_USER_ID"));
            userObj.put("mainCode", deptUserBean.getStr("DEPTUSER_MAIN_CODE"));
            userObj.put("userName", departmentList.get(0).getStr("USER_NAME"));
            array.add(userObj);
            openAccount(array.toJSONString(), departmentList);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public DynaBean doUpdate(DynaBean viewDeptUserBean, List<DynaBean> dynaBeanList, List<DynaBean> userDynaBeanList) throws DepartmentUserException, AccountException {
        String departmentId = viewDeptUserBean.getStr("JE_RBAC_DEPARTMENT_ID");
        String userId = viewDeptUserBean.getStr("JE_RBAC_USER_ID");

        String originalRoleIds = userDynaBeanList.get(0).getStr("USER_ROLE_ID");

        DynaBean userBeanTable = beanService.getResourceTable("JE_RBAC_USER");
        List<DynaBean> userColumns = userBeanTable.getDynaBeanList(BeanService.KEY_TABLE_COLUMNS);
        for (DynaBean eachColumnBean : userColumns) {
            if (viewDeptUserBean.containsKey(eachColumnBean.getStr("TABLECOLUMN_CODE"))) {
                userDynaBeanList.get(0).set(eachColumnBean.getStr("TABLECOLUMN_CODE"), viewDeptUserBean.get(eachColumnBean.getStr("TABLECOLUMN_CODE")));
            }
        }
        commonService.buildModelModifyInfo(userDynaBeanList.get(0));
        //若用户名称发生修改，则同步更新全局该用户名称
        updateUserName(viewDeptUserBean, userDynaBeanList, dynaBeanList);

        metaService.update(userDynaBeanList.get(0));
        //更新缓存
        rbacUserList.removeIf(dynaBean -> userId.equals(dynaBean.getStr("JE_RBAC_USER_ID")));
        rbacUserList.add(userDynaBeanList.get(0));

        //判断是否有账号，若有同步账号相关信息
        DynaBean account = metaService.selectOne("JE_RBAC_ACCOUNT", ConditionsWrapper.builder().eq("USER_ASSOCIATION_ID", userDynaBeanList.get(0).getStr("JE_RBAC_USER_ID")));
        if (account != null) {
            //校验唯一性
            rbacAccountService.checkAccountCodeUnique(account.getStr("JE_RBAC_ACCOUNT_ID"), viewDeptUserBean.getStr("USER_CODE"));
//            rbacAccountService.checkAccountPhoneUnique(account.getStr("JE_RBAC_ACCOUNT_ID"),viewDeptUserBean.getStr("USER_PHONE"));
//            rbacAccountService.checkAccountEmailUnique(account.getStr("JE_RBAC_ACCOUNT_ID"),viewDeptUserBean.getStr("USER_MAIL"));

            metaService.executeSql(
                    "UPDATE JE_RBAC_ACCOUNT SET ACCOUNT_CODE={0} , ACCOUNT_NAME={1},ACCOUNT_PHONE={2},ACCOUNT_MAIL={3},ACCOUNT_AVATAR={4} , ACCOUNT_SEX={5} WHERE JE_RBAC_ACCOUNT_ID ={6}",
                    userDynaBeanList.get(0).getStr("USER_CODE"),
                    userDynaBeanList.get(0).getStr("USER_NAME"),
                    userDynaBeanList.get(0).getStr("USER_PHONE"),
                    userDynaBeanList.get(0).getStr("USER_MAIL"),
                    userDynaBeanList.get(0).getStr("USER_AVATAR"),
                    userDynaBeanList.get(0).getStr("USER_SEX_CODE"),
                    account.getStr("JE_RBAC_ACCOUNT_ID"));
        }


        DynaBean deptUserBeanTable = beanService.getResourceTable("JE_RBAC_DEPTUSER");
        List<DynaBean> deptUserColumns = deptUserBeanTable.getDynaBeanList(BeanService.KEY_TABLE_COLUMNS);
        DynaBean deptUserBean = new DynaBean("JE_RBAC_DEPTUSER", false);
        for (DynaBean eachColumnBean : deptUserColumns) {
            if (viewDeptUserBean.containsKey(eachColumnBean.getStr("TABLECOLUMN_CODE"))) {
                deptUserBean.set(eachColumnBean.getStr("TABLECOLUMN_CODE"), viewDeptUserBean.get(eachColumnBean.getStr("TABLECOLUMN_CODE")));
            }
        }
        //处理人员排序字段
        DynaBean deptUser = metaService.selectOne("JE_RBAC_DEPTUSER", ConditionsWrapper.builder().eq("JE_RBAC_USER_ID", userId).eq("JE_RBAC_DEPARTMENT_ID", departmentId));
        if (!departmentId.equals(deptUser.getStr("JE_RBAC_DEPARTMENT_ID"))) {
            //修改部门需要同步修改部门用户排序
            List<Map<String, Object>> countList = metaService.selectSql("SELECT MAX(SY_ORDERINDEX) AS MAX_COUNT FROM JE_RBAC_DEPTUSER WHERE JE_RBAC_DEPARTMENT_ID ='" + departmentId + "'");
            int count = 0;
            if (countList.size() <= 0) {
                count = rbacDepartmentList.stream().filter(dept -> dept.getStr("JE_RBAC_DEPARTMENT_ID").equals(departmentId)).mapToInt(dept -> new Integer(String.valueOf(dept.getStr("DEPARTMENT_USER_ORDERINDEX")))).max().orElse(0);
//                countList = metaService.selectSql("SELECT MAX(DEPARTMENT_USER_ORDERINDEX) AS MAX_COUNT FROM JE_RBAC_DEPARTMENT WHERE JE_RBAC_DEPARTMENT_ID ='" + departmentId + "'");
            } else {
                count = Integer.valueOf(countList.get(0).get("MAX_COUNT").toString());
            }
            deptUserBean.set("SY_ORDERINDEX", count + 1);
        }

        //同步所属部门主管领导信息
        syncMajor(deptUserBean, dynaBeanList.get(0), userDynaBeanList.get(0), departmentId);
        if (!departmentId.equals(deptUser.getStr("JE_RBAC_DEPARTMENT_ID"))) {
            //若部门发生了改变，则调用变更部门
            JSONArray beanArr = new JSONArray();
            JSONObject beanObj = new JSONObject();
            beanObj.put("sourceDepartmentId", deptUser.getStr("JE_RBAC_DEPARTMENT_ID"));
            beanObj.put("targetDepartmentId", departmentId);
            beanObj.put("userId", deptUser.getStr("JE_RBAC_USER_ID"));
            //传递直属领导信息
            beanObj.put("type", "update");
            beanObj.put("directLeaderId", deptUserBean.getStr("DEPTUSER_DIRECTLEADER_ID"));
            beanObj.put("directLeaderName", deptUserBean.getStr("DEPTUSER_DIRECTLEADER_NAME"));
            beanArr.add(beanObj);
            rbacDepartmentUserService.changeDepartment(beanArr.toJSONString());
            //更新部门缓存
            rbacDepartmentList = metaService.select("JE_RBAC_DEPARTMENT", ConditionsWrapper.builder());
            //则更新 新部门人员数据，是否主管，直属领导
        } else {
            commonService.buildModelModifyInfo(deptUserBean);
            metaService.update(deptUserBean);
        }

        String currentRoleIds = userDynaBeanList.get(0).getStr("USER_ROLE_ID");
        if (!(originalRoleIds == null ? "" : originalRoleIds).equals(currentRoleIds)) {
            DynaBean accountBean = metaService.selectOne("JE_RBAC_ACCOUNT", ConditionsWrapper.builder().eq("USER_ASSOCIATION_ID", userId));
            if (accountBean != null) {
                rbacAccountRoleService.updateAccountRoles(accountBean.getStr("JE_RBAC_ACCOUNT_ID"), originalRoleIds, currentRoleIds, dynaBeanList.get(0).getStr("JE_RBAC_DEPARTMENT_ID"), dynaBeanList.get(0).getStr("DEPARTMENT_NAME"), deptUserBean.getStr("DEPTUSER_MAIN_CODE"));
            }
        }

        return metaService.selectOne("JE_RBAC_VDEPTUSER", ConditionsWrapper.builder()
                .eq("JE_RBAC_DEPARTMENT_ID", departmentId)
                .eq("JE_RBAC_USER_ID", userDynaBeanList.get(0).getStr("JE_RBAC_USER_ID")));
    }

    @Transactional(rollbackFor = Exception.class)
    public void openAccount(String userDeptIds, List<DynaBean> departmentList) throws AccountException {
        JSONArray array = JSONArray.parseArray(userDeptIds);
        for (int j = 0; j < array.size(); j++) {
            String departmentId = array.getJSONObject(j).getString("departmentId");
            String userId = array.getJSONObject(j).getString("userId");
            String userName = array.getJSONObject(j).getString("userName");
            //部门类型：主，分
            String mainCode = array.getJSONObject(j).getString("mainCode");

            rbacAccountService.checkAccountUnique(userId, array.size());

            String syStatus = "1";
            if (!Strings.isNullOrEmpty(array.getJSONObject(j).getString("status"))) {
                //创建用户调用传参，账号默认禁用
                syStatus = array.getJSONObject(j).getString("status");
            }
//            List<DynaBean> userDynaBeanList = rbacUserList.stream().filter(user -> user.getStr("JE_RBAC_USER_ID").equals(userId)).collect(Collectors.toList());
//            DynaBean userBean = metaService.selectOne("JE_RBAC_USER", ConditionsWrapper.builder().eq("JE_RBAC_USER_ID", userId));

            //需判断该人员所属部门状态
            DynaBean department = rbacDepartmentService.findById(departmentId);
            if (department == null) {
                throw new AccountException("该部门不存在！");
            }
            //判断当前所属部门是主部门，分部门），
            // 若所属部门是主部门被禁用，则不允许操作给提示；
            // 若当前是 分部门（被禁用，则给提示先启用，再去判断主部门状态））
            if ((mainCode.equals("1") || mainCode.equals("0")) && department.getStr("SY_STATUS").equals("0")) {
                //主部门,分部门被禁用
                if (array.size() == 1) {
                    throw new AccountException("该员工的上级部门已被禁用，请先启用！");
                } else {
                    throw new AccountException("该员工【" + userName + "】的上级部门已被禁用，请先启用！");
                }
            } else if (mainCode.equals("0") && department.getStr("SY_STATUS").equals("1")) {
                //分部门正常，则去判断当前用户主部门是否被禁用

                //判断主部门是否已经允许访问了，若已经允许，则分部门可以允许访问；若主部门没有允许访问，则提示 请先操作主部门允许访问。
                DynaBean userMainDeptBean = metaService.selectOne("JE_RBAC_DEPTUSER", ConditionsWrapper.builder().eq("JE_RBAC_USER_ID", userId).eq("DEPTUSER_MAIN_CODE", "1"));
                if (!rbacDepartmentUserService.checkMainDeptStatusById(userId)) {
                    if (array.size() == 1) {
                        throw new AccountException("该员工主部门的访问状态已被禁用，请先启用！");
                    } else {
                        throw new AccountException("请先开启该员工【" + userName + "】主部门的访问状态！");
                    }
                }

                //userid查询相关账号，然后查询是否有主部门关联的账号。
                List<DynaBean> accountBeanList = metaService.select("JE_RBAC_ACCOUNT", ConditionsWrapper.builder().eq("USER_ASSOCIATION_ID", userId));
                List<String> accountIds = new ArrayList<>();
                for (DynaBean accountBean : accountBeanList) {
                    accountIds.add(accountBean.getStr("JE_RBAC_ACCOUNT_ID"));
                }
                DynaBean accountMainDeptBean = metaService.selectOne("JE_RBAC_ACCOUNTDEPT", ConditionsWrapper.builder().eq("ACCOUNTDEPT_DEPT_ID", userMainDeptBean.getStr("JE_RBAC_DEPARTMENT_ID")).in("ACCOUNTDEPT_ACCOUNT_ID", accountIds));
                if (accountMainDeptBean == null) {
                    if (array.size() == 1) {
                        throw new AccountException("当前用户主部门未开通账号，请先开通当前用户主部门账号！");
                    } else {
                        throw new AccountException("当前用户【" + userName + "】主部门未开通账号，请先开通当前用户主部门账号！");
                    }

                }
            }
            if (syStatus.equals("1")) {
                //更改为允许访问
                enableUsers(departmentId, userId);
            }

            DynaBean orgBean = metaService.selectOne("JE_RBAC_ORG", ConditionsWrapper.builder()
                    .eq("JE_RBAC_ORG_ID", OrgType.DEPARTMENT_ORG_ID.getCode()));
            if (orgBean == null) {
                throw new AccountException("不存在部门机构！");
            }
            //获取到映射的资源表和资源表主键
            String tableCode = orgBean.getStr("ORG_RESOURCETABLE_CODE");
            String tableIdCode = orgBean.getStr("ORG_FIELD_PK");
            if (Strings.isNullOrEmpty(tableCode) || Strings.isNullOrEmpty(tableIdCode)) {
                throw new AccountException("Can't find the tableCode or pk code from the org mapping!");
            }

            //获取映射字段，账号名称、账号编码、账号手机、账号邮箱、账号头像
            String accountNameField = orgBean.getStr("ORG_ACCOUNT_NAME");
            String accountCodeField = orgBean.getStr("ORG_ACCOUNT_CODE");
            String accountPhoneField = orgBean.getStr("ORG_ACCOUNT_PHONE");
            String accountEmailField = orgBean.getStr("ORG_ACCOUNT_MAIL");
            String accountSexField = orgBean.getStr("ORG_ACCOUNT_SEX");
            String accountAvatarField = orgBean.getStr("ORG_ACCOUNT_AVATAR");
            String accountUserStatusField = orgBean.getStr("ORG_ACCOUNT_STATUS");

            String defaultPassword = systemSettingRpcService.findSettingValue("JE_SYS_PASSWORD");
            if (Strings.isNullOrEmpty(defaultPassword)) {
                throw new AccountException("系统设置默认密码为空！");
            }

//            DynaBean departmentBean = metaService.selectOne("JE_RBAC_DEPARTMENT", ConditionsWrapper.builder().eq("JE_RBAC_DEPARTMENT_ID", departmentId));
//            if (departmentBean == null) {
//                throw new AccountException("不存在的部门！");
//            }

            List<DynaBean> accountBeanList = metaService.select("JE_RBAC_ACCOUNT", ConditionsWrapper.builder().in("USER_ASSOCIATION_ID", userId));
            List<String> accountIds = new ArrayList<>();
            if (accountBeanList != null && accountBeanList.size() > 0) {
                for (DynaBean dynaBean : accountBeanList) {
                    accountIds.add(dynaBean.getStr("JE_RBAC_ACCOUNT_ID"));
                }
                metaService.executeSql("UPDATE JE_RBAC_ACCOUNT SET SY_STATUS='1' WHERE JE_RBAC_ACCOUNT_ID IN ({0})", accountIds);
                metaService.executeSql("UPDATE JE_RBAC_ACCOUNTDEPT SET SY_STATUS='1' WHERE ACCOUNTDEPT_DEPT_ID = {0} AND ACCOUNTDEPT_ACCOUNT_ID IN ({1})", departmentId, accountIds);
            }
            Map<String, DynaBean> hasAccountMap = new HashMap<>();
            for (DynaBean eachAccountBean : accountBeanList) {
                hasAccountMap.put(eachAccountBean.getStr("USER_ASSOCIATION_ID"), eachAccountBean);
            }

            List<DynaBean> userBeans = metaService.select(tableCode, ConditionsWrapper.builder().in(tableIdCode, userId));
            DynaBean accountBean;
            String accountId;
            List<DynaBean> accountDeptRoleModelList = new ArrayList<>();
            for (DynaBean eachUserBean : userBeans) {
                if (hasAccountMap.containsKey(eachUserBean.getStr(tableIdCode))) {
                    accountId = hasAccountMap.get(eachUserBean.getStr(tableIdCode)).getStr("JE_RBAC_ACCOUNT_ID");
                } else {
                    accountId = JEUUID.uuid();
                    accountBean = new DynaBean("JE_RBAC_ACCOUNT", true);
                    accountBean.set("JE_RBAC_ACCOUNT_ID", accountId);
                    accountBean.set("ACCOUNT_NAME", eachUserBean.getStr(accountNameField));
                    accountBean.set("ACCOUNT_CODE", eachUserBean.getStr(accountCodeField));
                    accountBean.set("ACCOUNT_OPENID", JEUUID.uuid());
                    accountBean.set("ACCOUNT_PASSWORD", SecureUtil.md5(defaultPassword));
                    accountBean.set("ACCOUNT_PHONE", eachUserBean.getStr(accountPhoneField));
                    accountBean.set("ACCOUNT_MAIL", eachUserBean.getStr(accountEmailField));
                    accountBean.set("ACCOUNT_SEX", eachUserBean.getStr(accountSexField));
                    accountBean.set("ACCOUNT_AVATAR", eachUserBean.getStr(accountAvatarField));
                    accountBean.set("USER_ASSOCIATION_ID", eachUserBean.getStr(tableIdCode));
                    accountBean.set("SY_TENANT_ID", orgBean.getStr("SY_TENANT_ID"));
                    accountBean.set("SY_TENANT_NAME", orgBean.getStr("SY_TENANT_NAME"));
                    accountBean.set("ACCOUNT_REMARK", "通过部门人员创建！");
                    accountBean.set("SY_ORG_ID", orgBean.getStr("JE_RBAC_ORG_ID"));
                    accountBean.set("SY_ORG_NAME", orgBean.getStr("ORG_NAME"));
                    accountBean.set("SY_STATUS", syStatus);
                    accountBean.set("USER_STATUS", eachUserBean.getStr(accountUserStatusField));
                    accountBean.set("ACCOUNT_LOCKED_STATUS", "1");
                    commonService.buildModelCreateInfo(accountBean);
                    metaService.insert(accountBean);
                }
                //新增账号部门关系
                insertAccountDept(eachUserBean.getStr(tableIdCode), accountId, departmentId, syStatus, departmentList);

                String roleIds = eachUserBean.getStr("USER_ROLE_ID");
                String roleNames = eachUserBean.getStr("USER_ROLE_NAME");
                if (Strings.isNullOrEmpty(roleIds) || Strings.isNullOrEmpty(roleNames)) {
                    continue;
                }

                List<String> roleIdList = Splitter.on(",").splitToList(roleIds);
                List<String> roleNameList = Splitter.on(",").splitToList(roleNames);

                DynaBean accountDeptRoleTempBean;
                for (int i = 0; i < roleIdList.size(); i++) {
                    int sysOrderIndex = -1;
                    List<Map<String, Object>> userOrderList = metaService.selectSql("SELECT MAX(SY_ORDERINDEX) AS MAX_COUNT FROM JE_RBAC_ACCOUNTROLE WHERE ACCOUNTROLE_ROLE_ID={0}", roleIdList.get(i));
                    if (userOrderList.size() > 0) {
                        sysOrderIndex = Integer.valueOf(userOrderList.get(0).get("MAX_COUNT").toString());
                    }
                    sysOrderIndex = (sysOrderIndex + 1);
                    accountDeptRoleTempBean = new DynaBean("JE_RBAC_ACCOUNTROLE", false);
                    accountDeptRoleTempBean.set("ACCOUNTROLE_ACCOUNT_ID", accountId);
                    accountDeptRoleTempBean.set("ACCOUNTROLE_DEPT_ID", departmentId);
                    accountDeptRoleTempBean.set("ACCOUNTROLE_DEPT_NAME", departmentList.get(0).getStr("DEPARTMENT_NAME"));
                    accountDeptRoleTempBean.set("ACCOUNTROLE_MAIN_CODE", mainCode);
                    accountDeptRoleTempBean.set("ACCOUNTROLE_ROLE_ID", roleIdList.get(i));
                    accountDeptRoleTempBean.set("ACCOUNTROLE_ROLE_NAME", roleNameList.get(i));
                    accountDeptRoleTempBean.set("SY_ORDERINDEX", sysOrderIndex);
                    accountDeptRoleTempBean.set("SY_CREATETIME", DateUtils.formatDateTime(new Date()));
                    accountDeptRoleModelList.add(accountDeptRoleTempBean);
                }
            }

            List<String> accountIdList = new ArrayList<>();
            for (DynaBean eachBean : accountDeptRoleModelList) {
                accountIdList.add(eachBean.getStr("ACCOUNTROLE_ACCOUNT_ID"));
            }

            List<DynaBean> existsAccountDeptRoleList = metaService.select("JE_RBAC_ACCOUNTROLE", ConditionsWrapper.builder()
                    .in("ACCOUNTROLE_ACCOUNT_ID", accountIdList)
                    .eq("ACCOUNTROLE_DEPT_ID", departmentId));
            List<DynaBean> needRemovedBeanList = new ArrayList<>();
            for (DynaBean eachExistsBean : existsAccountDeptRoleList) {
                for (DynaBean eachNeedInsertBean : accountDeptRoleModelList) {
                    if (eachExistsBean.getStr("ACCOUNTROLE_ACCOUNT_ID").equals(eachNeedInsertBean.getStr("ACCOUNTROLE_ACCOUNT_ID"))
                            && eachExistsBean.getStr("ACCOUNTROLE_DEPT_ID").equals(eachNeedInsertBean.getStr("ACCOUNTROLE_DEPT_ID"))
                            && eachExistsBean.getStr("ACCOUNTROLE_ROLE_ID").equals(eachNeedInsertBean.getStr("ACCOUNTROLE_ROLE_ID"))) {
                        needRemovedBeanList.add(eachNeedInsertBean);
                    }
                }
            }
            accountDeptRoleModelList.removeAll(needRemovedBeanList);
            metaService.insertBatch("JE_RBAC_ACCOUNTROLE", accountDeptRoleModelList);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void enableUsers(String departmentId, String userIds) {
        //人员关系
        List<String> userIdList = Arrays.asList(userIds.split(ArrayUtils.SPLIT));
        metaService.executeSql("UPDATE JE_RBAC_DEPTUSER SET SY_STATUS='1' WHERE JE_RBAC_DEPARTMENT_ID={0} AND JE_RBAC_USER_ID IN ({1})", departmentId, userIdList);
    }

    @Transactional(rollbackFor = Exception.class)
    public void insertAccountDept(String userId, String accountId, String departmentId, String status, List<DynaBean> departmentList) throws AccountException {
//        DynaBean departmentBean = metaService.selectOne("JE_RBAC_DEPARTMENT", ConditionsWrapper.builder().eq("JE_RBAC_DEPARTMENT_ID", departmentId));
//        if (departmentBean == null) {
//            throw new AccountException("不存在的部门！");
//        }
        DynaBean accountDeptBean = metaService.selectOne("JE_RBAC_ACCOUNTDEPT", ConditionsWrapper.builder()
                .eq("ACCOUNTDEPT_DEPT_ID", departmentId).eq("ACCOUNTDEPT_ACCOUNT_ID", accountId));
        if (accountDeptBean == null) {
            accountDeptBean = new DynaBean("JE_RBAC_ACCOUNTDEPT", false);
            accountDeptBean.set("JE_RBAC_ACCOUNTDEPT_ID", userId);
            accountDeptBean.set("ACCOUNTDEPT_DEPT_ID", departmentId);
            accountDeptBean.set("ACCOUNTDEPT_DEPT_NAME", departmentList.get(0).getStr("DEPARTMENT_NAME"));
            accountDeptBean.set("SY_CREATETIME", DateUtils.formatDateTime(new Date()));
            accountDeptBean.set("ACCOUNTDEPT_ACCOUNT_ID", accountId);
            accountDeptBean.set("SY_COMPANY_ID", departmentList.get(0).getStr("SY_COMPANY_ID"));
            accountDeptBean.set("SY_COMPANY_NAME", departmentList.get(0).getStr("SY_COMPANY_NAME"));
            accountDeptBean.set("SY_GROUP_COMPANY_ID", departmentList.get(0).getStr("SY_GROUP_COMPANY_ID"));
            accountDeptBean.set("SY_GROUP_COMPANY_NAME", departmentList.get(0).getStr("SY_GROUP_COMPANY_NAME"));
            accountDeptBean.set("SY_STATUS", status);
            metaService.insert(accountDeptBean);
        }
    }

    public void updateUserName(DynaBean deptUserBean, List<DynaBean> userDynaBeanList, List<DynaBean> deptDynaBeanList) {

        if (!userDynaBeanList.get(0).getStr("USER_NAME").equals(deptUserBean.getStr("USER_NAME"))) {
            //需要修改 公司表-管理员
            List<DynaBean> listManagerBean = metaService.select("JE_RBAC_COMPANY", ConditionsWrapper.builder().like("COMPANY_MANAGER_ID", "%" + deptUserBean.getStr("JE_RBAC_USER_ID") + "%"));
            if (listManagerBean != null && listManagerBean.size() > 0) {
                for (DynaBean eachCompanyBean : listManagerBean) {
                    List<String> managerIdList = Arrays.asList(eachCompanyBean.getStr("COMPANY_MANAGER_ID").split(ArrayUtils.SPLIT));
                    List<String> managerNameList = Arrays.asList(eachCompanyBean.getStr("COMPANY_MANAGER_NAME").split(ArrayUtils.SPLIT));
                    int indexCount = managerIdList.indexOf(deptUserBean.getStr("JE_RBAC_USER_ID"));
                    managerNameList.set(indexCount, deptUserBean.getStr("USER_NAME"));
                    metaService.executeSql("UPDATE JE_RBAC_COMPANY SET COMPANY_MANAGER_NAME={0} WHERE JE_RBAC_COMPANY_ID={1} ", StringUtils.join(managerNameList, ","), eachCompanyBean.getStr("JE_RBAC_COMPANY_ID"));
                }
            }
            //公司表-主管领导
            List<DynaBean> listBean = metaService.select("JE_RBAC_COMPANY", ConditionsWrapper.builder().like("COMPANY_MAJOR_ID", "%" + deptUserBean.getStr("JE_RBAC_USER_ID") + "%"));
            if (listBean != null && listBean.size() > 0) {
                for (DynaBean eachCompanyBean : listBean) {
                    List<String> zgIdList = Arrays.asList(eachCompanyBean.getStr("COMPANY_MAJOR_ID").split(ArrayUtils.SPLIT));
                    List<String> zgNameList = Arrays.asList(eachCompanyBean.getStr("COMPANY_MAJOR_NAME").split(ArrayUtils.SPLIT));
                    int indexCount = zgIdList.indexOf(deptUserBean.getStr("JE_RBAC_USER_ID"));
                    zgNameList.set(indexCount, deptUserBean.getStr("USER_NAME"));
                    metaService.executeSql("UPDATE JE_RBAC_COMPANY SET COMPANY_MAJOR_NAME={0} WHERE JE_RBAC_COMPANY_ID={1} ", StringUtils.join(zgNameList, ","), eachCompanyBean.getStr("JE_RBAC_COMPANY_ID"));
                }
            }

            //部门主管
//            List<DynaBean> listDeptBean = metaService.select("JE_RBAC_DEPARTMENT", ConditionsWrapper.builder().like("DEPARTMENT_MAJOR_ID", "%" + deptUserBean.getStr("JE_RBAC_USER_ID") + "%"));
            List<DynaBean> dynaBeanList = deptDynaBeanList.stream().filter(dept -> dept.getStr("DEPARTMENT_MAJOR_ID").contains(deptUserBean.getStr("JE_RBAC_USER_ID"))).collect(Collectors.toList());
            if (dynaBeanList != null && dynaBeanList.size() > 0) {
                for (DynaBean eachBean : dynaBeanList) {
                    List<String> zgIdList = Arrays.asList(eachBean.getStr("DEPARTMENT_MAJOR_ID").split(ArrayUtils.SPLIT));
                    List<String> zgNameList = Arrays.asList(eachBean.getStr("DEPARTMENT_MAJOR_NAME").split(ArrayUtils.SPLIT));
                    int indexCount = zgIdList.indexOf(deptUserBean.getStr("JE_RBAC_USER_ID"));
                    zgNameList.set(indexCount, deptUserBean.getStr("USER_NAME"));
                    metaService.executeSql("UPDATE JE_RBAC_DEPARTMENT SET DEPARTMENT_MAJOR_NAME={0} WHERE JE_RBAC_DEPARTMENT_ID={1} ", StringUtils.join(zgNameList, ","), eachBean.getStr("JE_RBAC_DEPARTMENT_ID"));
                    //更新部门缓存
                    rbacDepartmentList = metaService.select("JE_RBAC_DEPARTMENT", ConditionsWrapper.builder());
                }
            }

            //部门人员关联表（直接领导）
            metaService.executeSql("UPDATE JE_RBAC_DEPTUSER SET DEPTUSER_DIRECTLEADER_NAME={0} WHERE DEPTUSER_DIRECTLEADER_ID = {1}", deptUserBean.getStr("USER_NAME"), deptUserBean.getStr("JE_RBAC_USER_ID"));
            //更新部门缓存
            rbacDepartmentList = metaService.select("JE_RBAC_DEPARTMENT", ConditionsWrapper.builder());
            //todo 修改开发者人员名称

        }
    }

    public void syncMajor(DynaBean deptUserBean, DynaBean deptBean, DynaBean userBean, String departmentId) {
        //同步所属部门主管领导信息
        if (!Strings.isNullOrEmpty(deptUserBean.getStr("DEPTUSER_SFZG_CODE"))) {
            if (Strings.isNullOrEmpty(deptBean.getStr("DEPARTMENT_MAJOR_ID")) && deptUserBean.getStr("DEPTUSER_SFZG_CODE").equals("1")) {
                //更新部门主管信息
                metaService.executeSql("UPDATE JE_RBAC_DEPARTMENT SET DEPARTMENT_MAJOR_ID={0},DEPARTMENT_MAJOR_NAME={1} WHERE JE_RBAC_DEPARTMENT_ID={2} ", userBean.getStr("JE_RBAC_USER_ID"), userBean.getStr("USER_NAME"), departmentId);
                //更新部门缓存
                rbacDepartmentList = metaService.select("JE_RBAC_DEPARTMENT", ConditionsWrapper.builder());

            } else if (!Strings.isNullOrEmpty(deptBean.getStr("DEPARTMENT_MAJOR_ID"))) {
                //判断是否是主管,若 是主管
                if (deptUserBean.getStr("DEPTUSER_SFZG_CODE").equals("1")) {
                    //判断当前人是否在主管中，不在则追加
                    if (!deptBean.getStr("DEPARTMENT_MAJOR_ID").contains(userBean.getStr("JE_RBAC_USER_ID"))) {
                        List<String> majorIdList = Arrays.asList(deptBean.getStr("DEPARTMENT_MAJOR_ID").split(ArrayUtils.SPLIT));
                        List<String> newMajorIdList = new ArrayList(majorIdList);
                        newMajorIdList.add(userBean.getStr("JE_RBAC_USER_ID"));
                        List<String> majorNameList = Arrays.asList(deptBean.getStr("DEPARTMENT_MAJOR_NAME").split(ArrayUtils.SPLIT));
                        List<String> newMajorNameList = new ArrayList(majorNameList);
                        newMajorNameList.add(userBean.getStr("USER_NAME"));
                        metaService.executeSql("UPDATE JE_RBAC_DEPARTMENT SET DEPARTMENT_MAJOR_ID={0},DEPARTMENT_MAJOR_NAME={1} WHERE JE_RBAC_DEPARTMENT_ID={2} ", StringUtils.join(newMajorIdList, ","), StringUtils.join(newMajorNameList, ","), departmentId);
                        //更新部门缓存
                        rbacDepartmentList = metaService.select("JE_RBAC_DEPARTMENT", ConditionsWrapper.builder());
                    }
                } else {
                    //非主管，判断当前人是否在主管中，在则删除；
                    if (deptBean.getStr("DEPARTMENT_MAJOR_ID").contains(userBean.getStr("JE_RBAC_USER_ID"))) {
                        List<String> majorIdList = Arrays.asList(deptBean.getStr("DEPARTMENT_MAJOR_ID").split(ArrayUtils.SPLIT));
                        List<String> newMajorIdList = new ArrayList(majorIdList);
                        newMajorIdList.remove(userBean.getStr("JE_RBAC_USER_ID"));
                        List<String> majorNameList = Arrays.asList(deptBean.getStr("DEPARTMENT_MAJOR_NAME").split(ArrayUtils.SPLIT));
                        List<String> newMajorNameList = new ArrayList(majorNameList);
                        newMajorNameList.remove(userBean.getStr("USER_NAME"));
                        metaService.executeSql("UPDATE JE_RBAC_DEPARTMENT SET DEPARTMENT_MAJOR_ID={0},DEPARTMENT_MAJOR_NAME={1} WHERE JE_RBAC_DEPARTMENT_ID={2} ", StringUtils.join(newMajorIdList, ","), StringUtils.join(newMajorNameList, ","), departmentId);
                        //更新部门缓存
                        rbacDepartmentList = metaService.select("JE_RBAC_DEPARTMENT", ConditionsWrapper.builder());
                    }
                }
            }
        }
    }
}
